import subprocess
import uiautomator2 as u2
import os
import time
import win32api
import psutil
import re
from app.pingduoduo.shipin import AutoScanVideo
from app.jd.search import SearchGoods


class AutoPhone:

    def __init__(self, mock_exe_path, mock_adb_path):
        self.mock_exe_path = mock_exe_path
        self.mock_adb_path = mock_adb_path
        os.chdir(os.path.dirname(mock_exe_path))

        # 启动夜神浏览器
        self.hwnd = win32api.ShellExecute(0, 'open', self.mock_exe_path, '', '', 0)

        # 等待设备加载完成
        self.wait_device_start()

        # 重新加载atx，避免无法操作的问题，非 am instrument
        command = f"adb.exe shell  /data/local/tmp/atx-agent server -d"
        subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=1)

        # 获取夜神浏览器监控的端口
        command = f"adb.exe devices"
        ret = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=1)
        if ret.returncode == 0:
            stdout = ret.stdout.decode()
            ipaddress = re.compile("\d+\.\d+\.\d+\.\d+:\d+").findall(stdout)
            if ipaddress:
                self.ipaddress = ipaddress[0]
                print('获取ip地址: ', self.ipaddress)
            else:
                raise Exception('未能获取ip地址: ', stdout)
        else:
            print("error:", ret)

        self.devices = u2.connect(self.ipaddress)
        self.devices_info = self.devices.device_info

    @classmethod
    def wait_device_start(cls):
        while True:
            try:
                command = f"adb.exe shell getprop init.svc.bootanim"
                ret = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=1)
                stdout = ret.stdout.decode()
                if stdout.count("stop") != 0:
                    break
                else:
                    time.sleep(0.5)
            except Exception as e:
                time.sleep(1)
                continue

        time.sleep(2)

    def runserver(self):
        SearchGoods(self.devices).run()

    def __del__(self, *args, **kwargs):
        """退出关闭夜深浏览器"""
        for process in psutil.process_iter():
            if process.name() == 'Nox.exe':
                process.kill()


if __name__ == '__main__':
    # 启动 exe
    mock_installed_path = r"C:\Program Files (x86)\Nox\bin"
    mock_exe_path = os.path.join(mock_installed_path, "Nox.exe")
    mock_adb_path = os.path.join(mock_installed_path, "nox_adb.exe")

    phone = AutoPhone(mock_exe_path, mock_adb_path)
    phone.runserver()

    # while True:
    #     try:
    #         phone = AutoPhone(mock_exe_path, mock_adb_path)
    #         phone.runserver()
    #     except Exception as e:
    #         time.sleep(5)

